<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      .slider-bar {
        position: absolute;
        left: 50%;
        top: 300px;
        margin-left: 600px;
        width: 45px;
        height: 130px;
        background-color: pink;
      }

      .w {
        width: 1200px;
        margin: 10px auto;
      }

      .header {
        height: 150px;
        background-color: purple;
      }

      .banner {
        height: 250px;
        background-color: skyblue;
      }

      .main {
        height: 1000px;
        background-color: yellowgreen;
      }

      span {
        display: none;
        position: absolute;
        bottom: 0;
      }
    </style>
  </head>

  <body>
    <div class="slider-bar">
      <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
      // 获取元素
      var sliderBar = document.querySelector(".slider-bar");
      var banner = document.querySelector(".banner");
      var goBack = document.querySelector(".goBack");
      // 获取 main盒子的offsetTop值
      var mainTop = document.querySelector(".main").offsetTop;
      // 获取 banner盒子的offsetTop值
      var bannerTop = banner.offsetTop;
      // 获取 sliderBar盒子的offsetTop值
      var sliderBarTop = sliderBar.offsetTop;
      var fixedTop = sliderBarTop - bannerTop;
      //   console.log(banner.offsetTop);
      // 给页面注册onscroll 事件
      document.addEventListener("scroll", function () {
        // 如果页面向上卷去出去的距离 大于等于 banner盒子的offsetTop值 就将 sliderBar修改为 固定定位 否则设置为绝对定位
        if (window.pageYOffset >= bannerTop) {
          sliderBar.style.position = "fixed";
          sliderBar.style.top = fixedTop + "px";
        } else {
          sliderBar.style.position = "absolute";
          sliderBar.style.top = 300 + "px";
        }

        if (window.pageYOffset >= mainTop) {
          goBack.style.display = "block";
        } else {
          goBack.style.display = "none";
        }
      });
    </script>
  </body>
</html>
